package com.cszy.yydqbfq.viewmodel
import AudioLoadRepository
import android.content.Context
import android.graphics.Color
import android.util.Log
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.viewpager2.widget.ViewPager2
import com.hbcysd.qybfq.R

import com.cszy.yydqbfq.base.BaseViewModel
import com.cszy.yydqbfq.bean.AudioItemBean
import com.cszy.yydqbfq.bean.IndexGridBean
import com.cszy.yydqbfq.utils.SpUtils
import com.hjq.shape.view.ShapeView
import com.hlyj.http.base.tool.lib_hlyj_base.bean.BaseResult
import com.hlyj.http.base.tool.lib_hlyj_base.bean.HuaFeiSearchBean
import com.hlyj.http.base.tool.lib_hlyj_base.bean.HuaFeiSearchResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.bean.music.MusicListBean
import com.hlyj.http.base.tool.lib_hlyj_base.net.ApiCallback
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans

import com.lzx.starrysky.SongInfo
import com.ok.common.api.GlobalApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.litepal.LitePal
class IndexViewModel:BaseViewModel() {
    private lateinit var AudioLoadRespository: AudioLoadRepository
    fun init(context: Context) {
        AudioLoadRespository = AudioLoadRepository(context.applicationContext)
    }

    private var bannerJob: Job? = null
    private var currentPosition = 0
    private var bannerSize = 0

    /**
     * 开始Banner自动轮播
     * @param viewPager ViewPager2组件
     * @param indicators 指示器数组
     * @param interval 轮播间隔时间(毫秒)
     */
    fun startBannerAutoScroll(viewPager: ViewPager2, indicators: Array<ShapeView>?, interval: Long = 3000L) {
        stopBannerAutoScroll()

        bannerJob = viewModelScope.launch {
            while (isActive) { // 使用 isActive 检查协程状态
                delay(interval)
                if (bannerSize > 1 && isActive) { // 再次检查协程状态
                    currentPosition = (currentPosition + 1) % bannerSize
                    // 确保UI更新在主线程执行
                    withContext(Dispatchers.Main) {
                        viewPager.currentItem = currentPosition
                        indicators?.let {
                            updateIndicators(it, currentPosition)
                        }
                    }
                }
            }
        }
    }


    /**
     * 停止Banner自动轮播
     */
    fun stopBannerAutoScroll() {
        bannerJob?.cancel()
        bannerJob = null
    }

    /**
     * 设置Banner数据大小
     */
    fun setBannerSize(size: Int) {
        bannerSize = size
        currentPosition = 0
    }

    /**
     * 更新指示器状态
     */
     fun updateIndicators(indicators: Array<ShapeView>, position: Int) {
        for (i in indicators.indices) {
            if (i == position) {
                // 选中状态
                indicators[i].shapeDrawableBuilder.solidColor = Color.parseColor("#82F7ED")
            } else {
                // 未选中状态
                indicators[i].shapeDrawableBuilder.solidColor = Color.parseColor("#8A9199")// 或者你定义的颜色 @color/tabunselect
            }
            indicators[i].shapeDrawableBuilder.buildBackgroundDrawable()
        }
    }


    /**
     * 从本地获取音频列表(有则从数据库获取)
     */
    suspend fun getAudioInfoListSync(): List<AudioItemBean> = withContext(Dispatchers.IO) {
        try {

            val localList = LitePal.findAll(AudioItemBean::class.java)
            if (localList.isNotEmpty()) {
                return@withContext localList
            }
            val remoteList = AudioLoadRespository.loadAudioFiles()
            LitePal.saveAll(remoteList)
            remoteList
        } catch (e: Exception) {
            Log.e("AudioViewModel", "Error fetching audio list", e)
            emptyList()
        }
    }

    /**
     * 从本地获取音频列表(直接从本地更新)
     */
    suspend fun getAudioInfoListSync_onlylocal(): List<AudioItemBean> = withContext(Dispatchers.IO) {
        try {

            val remoteList = AudioLoadRespository.loadAudioFiles()
            val localList = LitePal.findAll(AudioItemBean::class.java)
            if (localList.isNotEmpty()) {
                return@withContext localList
            }
            LitePal.saveAll(remoteList)
            remoteList
        } catch (e: Exception) {
            Log.e("AudioViewModel", "Error fetching audio list", e)
            emptyList()
        }
    }



    private val _queryResult = MutableLiveData<List<MusicListBean?>?>()
    val queryMusicResult: LiveData<List<MusicListBean?>?> = _queryResult

    private val _errorMessage = MutableLiveData<String>()
    val errorMessage: LiveData<String> = _errorMessage
    //获取所有音频数据
    fun queryMusic() {
        var list= LitePal.findAll(MusicListBean::class.java)
        if (list.isNotEmpty()){
            _queryResult.postValue(list)

        }else{
            GlobalApi.getMusicList("",object :
                ApiCallback<BaseResult<List<MusicListBean?>?>> {


                override fun onSuccess(result: BaseResult<List<MusicListBean?>?>) {
                    LitePal.saveAll(result.data as List<MusicListBean>)
                    _queryResult.postValue(result?.data)
                }

                override fun onFailure(errorMessage: String) {
                    _errorMessage.postValue(errorMessage)
                }

                override fun onFinish() {

                }

            })
        }

    }
   //获取category为流行的音频数据从数据库或者网络获取
    fun queryMusicByCategory(category: String) {
       // 分割分类字符串（如 "流行,说唱" -> ["流行", "说唱"]）
       val categories = category.split(",").map { it.trim() }

       // 构建 SQL 条件（匹配任意一个分类）
       val whereClause = categories.joinToString(" OR ") { "category LIKE ?" }
       val whereArgs = categories.map { "%$it%" }.toTypedArray()

       // 本地数据库查询
       val list = LitePal.where(whereClause, *whereArgs).find(MusicListBean::class.java)
       if (list.isNotEmpty()){
            _queryResult.postValue(list)
        }else{
            GlobalApi.getMusicList(category,object :
                ApiCallback<BaseResult<List<MusicListBean?>?>> {
                override fun onSuccess(result: BaseResult<List<MusicListBean?>?>) {
                    _queryResult.postValue(result?.data)

                }

                override fun onFailure(errorMessage: String) {
                    _errorMessage.postValue(errorMessage)
                }

                override fun onFinish() {

                }

            })
        }
    }


    /**
     * 获取首页gridbean数据
     */
    fun getIndexGridData():List<IndexGridBean>{
        return listOf(
            IndexGridBean("流行", R.mipmap.ic_index_gradbg,R.mipmap.ic_sub_index_grad,"旋律简洁流畅"),
            IndexGridBean("怀旧",R.mipmap.ic_huaijiu_index, R.mipmap.ic_sub_huaijiu_index,"是回忆加了分"),
            IndexGridBean("摇滚",R.mipmap.ic_yaogun_index,R.mipmap.ic_sub_yaogun_index,"国摇天花板"),
            IndexGridBean("民谣",R.mipmap.ic_mingyao_index,R.mipmap.ic_sub_mingyao_index,"人间烟火气"),
            IndexGridBean("说唱",R.mipmap.ic_shuochang_index,R.mipmap.ic_sub_shuochang_index,"动感的鼓点",),
            IndexGridBean("国风",R.mipmap.ic_guofeng_index,R.mipmap.ic_sub_guofeng_index,"清韵诉流年"),
        )
    }


    //本地获取的音乐转songInfo
    fun convertToLocalSongInfoList(musicList: List<AudioItemBean>): List<SongInfo> {
        val songInfoList = musicList.mapIndexed { index, audioItem ->
            SongInfo().apply {
                songId = index.toString() // Using the actual ID from AudioItemBean
                songUrl = audioItem.path ?: ""
                songName = audioItem.title ?: ""
                artist = audioItem.artist ?: ""
                songCover = "" // AudioItemBean doesn't have imageUrl, so we set empty
                duration = audioItem.duration // Convert Long to Int if needed
                decode = false
            }
        }
        return songInfoList
    }

    /**
     * taglist
     */
    fun getRandomTag(): String {
        return getTagList().random()
    }

    fun getTagList(): List<String> {
        return listOf(
            "重温经典",
            "平凡岁月",
            "流行金曲"
        )
    }
}